﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using Top.Api;
using Top.Api.Domain;
using Top.Api.Request;
using Top.Api.Response;
using System.Collections;
using DBControl;
using System.Data;
using System.Net;
using System.IO;

namespace KSGJ.AjaxCommand
{
    /// <summary>
    /// setPriceQuick 的摘要说明
    /// </summary>
    public class setPriceQuick : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        #region "Fields and Properties"
        /// <summary>
        /// 人群的名字
        /// </summary>
        private static ITopClient client = new DefaultTopClient(WebConfigurationManager.AppSettings["AppUrl"].ToString(), WebConfigurationManager.AppSettings["AppKey"].ToString(), WebConfigurationManager.AppSettings["AppSecret"].ToString());
        public string myTagName = "";
        public string errMsg = "";
        #endregion

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            SqlDbHelper sdh = new SqlDbHelper();
            string maijia = context.Request.Form["changeto"];
            myTagName = maijia.Replace(":", "").Replace("-", "");
            string goodid = context.Request.Form["goodid"];
            string goodprice = context.Request.Form["price"];
            string usersessionkey = context.Session["sessionKey"].ToString();
            int gaijiaovertime = int.Parse(context.Request.Form["overtime"]);
            //获得当前用户所有的人群
            List<UserTag> allTag = getTag(usersessionkey);
            //根据人群数开始循环
            foreach (var item in allTag)
            {
                //根据人群ID查询数据库中所有的优惠
                string overtag = "SELECT * FROM Promotion WHERE TagID = '" + item.TagId + "' ORDER BY Endtime";
                //能否删除人群的表示
                bool isdeltag = true;
                //执行SQL语句查询
                DataTable dt = sdh.ExecuteDataTable(overtag);
                //根据获得的优惠数量循环
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //判断优惠是否过期
                    if (DateTime.Compare(DateTime.Parse(dt.Rows[i]["Endtime"].ToString()), DateTime.Now) >= 0)
                    {
                        //如有一个优惠未过期，设置删除人群表示为否表示不能删除该人群
                        isdeltag = false;
                        break;
                    }
                    else//过期
                    {
                        //删除优惠信息
                        bool delp = delPromotion(long.Parse(dt.Rows[i]["Pid"].ToString()), usersessionkey);
                        if (delp)
                        {
                            //同时删除数据库中的这条优惠记录
                            string delpro = "DELETE Promotion WHERE Pid = '" + dt.Rows[i]["Pid"].ToString() + "'";
                            sdh.ExecuteNonQuery(delpro);
                        }
                    }
                }
                //判断能否删除人群
                if (isdeltag)
                {
                    //删除人群标签
                    bool delt = delTag(usersessionkey, item.TagId);
                }
            }
            //获得当前用户删除人群后的所有人群
            List<UserTag> listTag = getTag(usersessionkey);
            //如果人群数大于10则不能添加人群与优惠需要清除已过期的人群再试。
            if (allTag.Count >= 10)
            {
                errMsg = "优惠的人数过多，请点击[清除过期人群]按钮后再试!";
            }
            else
            {
                //判断人群中是否存在您输入的人群名
                UserTag mytag = listTag.Find(delegate(UserTag ut) { return ut.TagName == myTagName; });
                //不存在，添加人群并添加优惠
                if (mytag == null)
                {
                    UserGetRequest usreq = new UserGetRequest();
                    usreq.Nick = maijia;
                    usreq.Fields = "user_id";
                    UserGetResponse usresponse = client.Execute(usreq);
                    if (usresponse.User == null)
                    {
                        errMsg = "输入的用户名不存在，请重新输入！";
                    }
                    else
                    {
                        MarketingTagAddRequest tagaddreq = new MarketingTagAddRequest();
                        tagaddreq.TagName = myTagName;
                        tagaddreq.Description = "快捷改价";
                        MarketingTagAddResponse tagaddresponse = client.Execute(tagaddreq, usersessionkey);
                        if (tagaddresponse.IsError)
                        {
                            errMsg = tagaddresponse.SubErrMsg;
                        }
                        else
                        {
                            addTargetuser(tagaddresponse.UserTag.TagId, maijia, usersessionkey);//添加目标人群
                            Promotion p; DateTime starttime; DateTime endtime;
                            addPromotion(goodid, "PRICE", goodprice, tagaddresponse.UserTag.TagId, usersessionkey, gaijiaovertime, out p, out starttime, out endtime);//添加优惠
                            if (p != null)
                            {
                                string promotionNew = "INSERT INTO Promotion(Pid,Numid,DiscountType,DiscountValue,Startime,Endtime,Promotiontitle,TagID)";
                                promotionNew += "VALUES(" + p.PromotionId + "," + p.NumIid + ",'PRICE','" + goodprice + "','" + starttime + "','" + endtime + "','" + p.PromotionTitle + "'," + tagaddresponse.UserTag.TagId + ")";
                                sdh.ExecuteNonQuery(promotionNew);
                            }
                        }
                    }
                }
                else
                {
                    Promotion p; DateTime starttime; DateTime endtime;
                    addPromotion(goodid, "PRICE", goodprice, mytag.TagId, usersessionkey, gaijiaovertime, out p, out starttime, out endtime);//添加优惠
                    if (p != null)
                    {
                        string promotionNew = "INSERT INTO Promotion(Pid,Numid,DiscountType,DiscountValue,Startime,Endtime,Promotiontitle,TagID)";
                        promotionNew += "VALUES(" + p.PromotionId + "," + p.NumIid + ",'PRICE','" + goodprice + "','" + starttime + "','" + endtime + "','" + p.PromotionTitle + "'," + mytag.TagId + ")";
                        sdh.ExecuteNonQuery(promotionNew);
                    }
                }
            }
            if (errMsg != "")
            {
                context.Response.Write(errMsg);
                context.Response.End();
            }
            else
            {
                context.Response.Write("ok");
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 删除当前会话用户下的本应用所创建的人群
        /// </summary>
        /// <param name="sessionkey">sessionkey</param>
        private bool delTag(string sessionkey, long tid)
        {
            MarketingTagDeleteRequest utd = new MarketingTagDeleteRequest();
            utd.TagId = tid;
            MarketingTagDeleteResponse utr = client.Execute(utd, sessionkey);
            if (utr.IsError)
            {
                errMsg = utr.SubErrMsg;
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 获取当前会话用户下的本应用所创建的人群
        /// </summary>
        /// <returns></returns>
        protected List<UserTag> getTag(string sessionkey)
        {
            MarketingTagsGetRequest tagget = new MarketingTagsGetRequest();
            tagget.Fields = "tag_id,tag_name,create_date,description";
            MarketingTagsGetResponse tagresp = client.Execute(tagget, sessionkey);
            return tagresp.UserTags;
        }

        /// <summary>
        /// 添加目标用户
        /// </summary>
        /// <param name="gid">人群ID</param>
        /// <param name="usnick">要添加的用户昵称</param>
        /// <returns></returns>
        private Boolean addTargetuser(long gid, string usnick, string sessionkey)
        {
            MarketingTaguserAddRequest req = new MarketingTaguserAddRequest();
            req.TagId = gid;
            req.Nick = usnick;
            MarketingTaguserAddResponse response = client.Execute(req, sessionkey);
            if (response.IsError) { errMsg = response.SubErrMsg; return false; }
            return true;
        }

        /// <summary>
        /// 删除目标用户
        /// </summary>
        /// <param name="gid">人群ID</param>
        /// <param name="usnick">要删除的用户昵称</param>
        /// <returns></returns>
        private Boolean delTargetuser(long gid, string usnick, string sessionkey)
        {
            MarketingTaguserDeleteRequest req = new MarketingTaguserDeleteRequest();
            req.TagId = gid;
            req.Nick = usnick;
            MarketingTaguserDeleteResponse response = client.Execute(req, sessionkey);
            if (response.IsError) { errMsg = response.SubErrMsg; return false; }
            return true;
        }

        /// <summary>
        /// 添加定向优惠
        /// </summary>
        /// <param name="numid">商品ID</param>
        /// <param name="discountype">折扣类型，有打折DISCOUNT和优惠价PRICE</param>
        /// <param name="discountvalue">折扣值,打折为x.x的百分比值，优惠价直接填价格</param>
        /// <param name="gid">人群ID</param>
        /// <returns></returns>
        private Boolean addPromotion(string numid, string discountype, string discountvalue, long gid, string sessionkey, int priceovertime, out Promotion outpromotion, out DateTime st, out DateTime et)
        {
            
            DateTime endtime = DateTime.Now.AddMinutes(priceovertime);
            et = endtime;
            st = DateTime.Now;
            MarketingPromotionAddRequest req = new MarketingPromotionAddRequest();
            req.NumIids = numid;
            req.DiscountType = discountype;
            req.DiscountValue = discountvalue;
            req.StartDate = st;
            req.EndDate = et;
            req.PromotionTitle = "快速改价";
            req.PromotionDesc = "您的优惠持续到今天的" + et.Hour + "点" + et.Minute + "分";
            req.TagId = gid;
            MarketingPromotionAddResponse response = client.Execute(req, sessionkey);
            if (response.IsError) { errMsg = response.SubErrMsg; outpromotion = null; return false; }
            outpromotion = response.Promotions[0];
            return true;
        }

        /// <summary>
        /// 删除定向优惠策略
        /// </summary>
        /// <param name="pid">优惠策略ID</param>
        /// <returns></returns>
        private Boolean delPromotion(long pid, string sessionkey)
        {
            MarketingPromotionDeleteRequest req = new MarketingPromotionDeleteRequest();
            req.PromotionId = pid;
            MarketingPromotionDeleteResponse response = client.Execute(req, sessionkey);
            if (response.IsError) { errMsg = response.SubErrMsg; return false; }
            return true;
        }

        /// <summary>
        /// 根据商品和人群查询定向优惠策略
        /// </summary>
        /// <param name="gid">人群ID</param>
        /// <param name="numid">商品ID</param>
        /// <returns></returns>
        private List<Promotion> getTaobaoPromotion(long gid, string numid, string sessionkey)
        {
            MarketingPromotionsGetRequest req = new MarketingPromotionsGetRequest();
            req.Fields = "promotion_id, promotion_title, num_iid, discount_type, discount_value, end_date, tag_id, status";
            //req.TagId = gid;
            req.NumIid = numid;
            //req.Status = "ACTIVE";
            MarketingPromotionsGetResponse response = client.Execute(req, sessionkey);
            return response.Promotions;
            //return response.Promotions.FindAll(delegate(Promotion p) { return DateTime.Parse(p.EndDate) < DateTime.Now && p.Status == "ACTIVE"; });
        }   
    }
}